

using System;
using System.IO;

namespace JTC.MiniCommerce.Core.IO {
  
  public class FileWriter {
  
    #region Constants
    
    private const string PATH = "path";
    private const string FILE_EXISTS = "The file already exists.";
    private const string DIRECTORY_DOES_NOT_EXIST = "Directory does not exist: {0}";
    
    #endregion
    
    #region Methods
    
    #region Public

    public void Write(string path, Stream stream) {
      Validator.ValidateStringArgumentIsNotNullOrEmptyString(path, PATH);
      if(File.Exists(path)) {
        throw new ArgumentException(FILE_EXISTS, PATH);
      }

      string directoryName = Path.GetDirectoryName(path);
      if(!Directory.Exists(directoryName)) {
        throw new DirectoryNotFoundException(string.Format(DIRECTORY_DOES_NOT_EXIST, directoryName));
      }

      FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
      byte[] buffer = new byte[4096];
      int bytesRead;
      while((bytesRead = stream.Read(buffer, 0, 4096)) > 0) {
        fileStream.Write(buffer, 0, bytesRead);
      }
      fileStream.Flush();
      fileStream.Close();
    }
    
    #endregion
    
    #endregion
    
  }
}
